package com.dtranx.tools.locale.config;

import com.alibaba.fastjson.JSONObject;
import com.dtranx.tools.commons.vo.AbstractLocal;
import com.dtranx.tools.commons.vo.ResponseResult;
import com.dtranx.tools.locale.utils.LocalUtils;
import com.dtranx.tools.locale.vo.JsonFileVo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.*;

@Slf4j
@Component
public class LocalFactory {

    private static final String LOCALE = "locale";

    private static final String CLASSPATH = "classpath:";

    static {
        Map<String, Map<String, String>> initMap = initMap();
        ServiceLoader s = ServiceLoader.load(AbstractLocal.class);
        Iterator i = s.iterator();
        while (i.hasNext()) {
            AbstractLocal object = (AbstractLocal) i.next();
            if (object instanceof LocalUtils) {
                ((LocalUtils) object).setLocaleMap(initMap);
            }
            ResponseResult.abstractLocal = object;
        }
        System.out.println("初始化结束");
    }

    /**
     * 获取 locale 下的所有json文件
     *
     * @return
     * @throws Exception
     */
    public static List<JsonFileVo> loadJsonFiles() throws Exception {
        List<JsonFileVo> localeResources = new ArrayList<>();
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources(ResourceUtils.CLASSPATH_URL_PREFIX + LOCALE + "/*.json");
        if(resources != null && resources.length > 0){
            for (Resource resource : resources) {
                localeResources.add(JsonFileVo.builder().fileName(resource.getFilename()).inputStream(resource.getInputStream()).build());
            }
        }
        return localeResources;
    }


    /**
     * 初始化
     */
    private static Map<String, Map<String, String>> initMap() {
        Map<String, Map<String, String>> localeMap = new HashMap<>();
        // 目录下下所有json文件 封装文本到localeMap
        List<JsonFileVo> fileDirectory;
        try {
            log.info("当前的类加载器：{}", ClassUtils.getDefaultClassLoader());
            log.info("LocalFactory的类加载器：{}", LocalFactory.class.getClassLoader());
            fileDirectory = loadJsonFiles();
            if (CollectionUtils.isEmpty(fileDirectory)) {
                return localeMap;
            }
        } catch (Exception e) {
            log.error("未获取到本地化文件：{}", e);
            return localeMap;
        }
        for (JsonFileVo vo : fileDirectory) {
            log.error("资源文件数据 名称:{}", vo.getFileName());
            String jsonStr = readJsonFile(vo.getInputStream());
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if (jsonObject == null) {
                continue;
            }
            Map<String, String> map = Maps.newHashMap();
            for (Map.Entry<String, Object> objectEntry : jsonObject.entrySet()) {
                map.put(objectEntry.getKey(), objectEntry.getValue() == null ? null : objectEntry.getValue().toString());
            }
            localeMap.put(vo.getFileName().split("\\.")[0].toLowerCase(), map);
        }
        log.info("本地化静态map：{}", localeMap);
        return localeMap;
    }

    public static String readJsonFile(InputStream inputStream) {
        try (Reader reader = new InputStreamReader(inputStream, "utf-8")) {
            int ch;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            String jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            log.error("读取文件报错：{}", e);
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        ResponseResult.failure("失败", 101);
    }

}
